﻿using System.Net;
using System.Security.Claims;
using HuaskyWebAPI.Core.Exceptions;
using HuaskyWebAPI.Core.Session;
using Microsoft.AspNetCore.Authentication;


namespace HuaskyWebAPI.Web.Core.Auth;

class AuthHandler : IAuthenticationHandler
{
	public const string SchemeName = "HuaskyWebAPI.Auth";

	AuthenticationScheme _scheme;
	HttpContext          _context;

	/// <summary>
	/// 初始化认证
	/// </summary>
	public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
	{
		_scheme  = scheme;
		_context = context;

		return Task.CompletedTask;
	}

	/// <summary>
	/// 认证处理
	/// </summary>
	public Task<AuthenticateResult> AuthenticateAsync()
	{
		// 权限验证时，通过本地方式，获取会话信息，没有获取到信息或者会话状态异常，则抛出
		var session = UserSession.GetSessionData(_context.Request, false);
		if (session.State != AuthState.Normal)
		{
			return Task.FromResult(AuthenticateResult.Fail("auth failed"));
		}

		var ticket = GetAuthTicket(session);
		return Task.FromResult(AuthenticateResult.Success(ticket));
	}

	AuthenticationTicket GetAuthTicket(SessionData session)
	{
		var claimsIdentity = new ClaimsIdentity(session.Claims, SchemeName);
		var principal = new ClaimsPrincipal(claimsIdentity);
		return new AuthenticationTicket(principal, _scheme.Name);
	}

	/// <summary>
	/// 权限不足时的处理
	/// </summary>
	public Task ForbidAsync(AuthenticationProperties properties)
	{
		_context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
		return Task.CompletedTask;
	}

	/// <summary>
	/// 未登录时的处理
	/// </summary>
	public Task ChallengeAsync(AuthenticationProperties properties)
	{
		_context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
		return Task.CompletedTask;
	}
	
	//https://learn.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore-7.0
}